<?php
/**
 * Display the list of available widgets and allow the
 * user to add/remove them from the dashboard
 * 
 * @author Xavier VILAIN
 * @package Hive
 * @license #hive-dashboard#
 * 
 */

use Fox\Generator;
use Fox\Html\Button\Help;
use Fox\Html\CheckBox;
use Fox\Html\Block;
use Fox\Html\DropList;
use Fox\Html\Screen;

$xview = Xview::instance();
$user = User::current();
$widgets = $user->getPrefs(User::PREFERENCE_WIDGETS);
$widgetExists = array();
$widgetUserPreference = array();
$widgetList = array();
if(!empty($widgets)) {
	$widgets = json_decode($widgets,true);
	foreach($widgets as $widgetPreference) {
		$widgetExists['bCheck_'.$widgetPreference['widgetid']] = true;
		$widgetUserPreference[$widgetPreference['widgetid']]= $widgetPreference;
		$widgetList[$widgetPreference['column']][$widgetPreference['position']] = $widgetPreference;
	}
} 
$categories = Fox\Dao::finder(Hive\Widget\Category::className())
				->orderBy('position')
				->find();
				
$screen = new Screen('sDashboardCustomize','update',null,true,Generator::redirect('?'));
foreach($categories as $category) {
	$widgets = $category->widgets();
	if(count($widgets) > 0) {
		$block = new Block('bCat_'.$category->getId(),$category->label());
		foreach($widgets as $widget) {
			$block->add(new CheckBox('bCheck_'.$widget->getId(),null))
					->labelAutoHeight()
					->labelSize(200)
					->label($widget->label())
					->add(new Help('hlp_'.$widget->getId(),$widget->description()));
		}
		$screen->add($block);
	}
}
$screen->initialize($widgetExists);
if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors()) {
		foreach($fields as $fieldname => $value) {
			$widgetid = substr($fieldname,7);
			if(isset($widgetUserPreference[$widgetid]) && !$value) {
				unset($widgetUserPreference[$widgetid]);
			}
			if(!isset($widgetUserPreference[$widgetid]) && $value) {
				// Add Widget to User Preferences
				if(count($widgetList) > 0) {
					$column = count($widgetList);
					$row = count($widgetList[$column]) +1;
					$widgetUserPreference[$widgetid] = array('widgetid' => $widgetid,'column' => $column,'position' => $row);
				} else {
					$widgetUserPreference[$widgetid] = array('widgetid' => $widgetid,'column' => 1,'position' => 1); 
				}
			}
		}
		if(count($widgetUserPreference) > 0) {
			$widgetUserPreference = json_encode($widgetUserPreference);
		} else {
			$widgetUserPreference = null;
		}
		$user->setPrefs(User::PREFERENCE_WIDGETS,$widgetUserPreference);
		Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_SAVED_PREFERENCES));
	}
	echo $xview->messages(true,true);
	exit;
}
$popup = new Fox\Popup('dashboardCustomize',
			Msg(Hive::BUNDLE,Hive::DASHBOARD_CUSTOMIZE),
			$screen
	);
echo $popup->display();